var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');  // 确保路径正确
var { expressjwt: jwt } = require("express-jwt"); // 解密
var fileUpload = require('express-fileupload'); // 引入 express-fileupload 中间件
const secretKey = 'aVerySecretKey_123';

var app = express();

app.use(jwt({
  secret: secretKey,
  algorithms: ['HS256'],
}).unless({
  path: [
    /^\/users\/register/,
    /^\/users\/login/,
    /^\/users\/add_user/, 
    /^\/users\/list/, 
    /^\/users\/add_album/, 
    /^\/users\/add_list/,
     /^\/users\/del_album/,
    /^\/public/,
    /^\/users\/pud_album/,
    /^\/users\/sel_album/,
     /^\/users\/add_img/,
     /^\/users\/del_img/,
     /^\/users\/get_app/,
     /^\/users\/add_app/,
     /^\/users\/del_app/,
     /^\/users\/get_reply/,
     /^\/users\/add_reply/,
  ],
}));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(fileUpload()); // 使用 fileUpload 中间件

app.use('/public',express.static('public'));
app.get('/', (req, res) => {
  res.send({
    code: 200,
    data: result
});
});

app.use('/', indexRouter);
app.use('/users', usersRouter);  


app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;